"""
运动健身管理系统 - 后台管理端
端口：8001
功能：管理员管理、角色管理、资源管理、权限控制、业务数据查询
"""
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from tortoise import Tortoise
from config.config import TORTOISE_ORM
import time


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时：初始化数据库连接
    await Tortoise.init(config=TORTOISE_ORM)
    await Tortoise.generate_schemas()
    print("✅ 数据库连接成功")
    
    # 启动时：初始化 WebSocket Manager 的 Redis 连接
    from utils.webSocket import wbs
    try:
        await wbs.init_redis()
        print("✅ WebSocket Manager Redis 连接成功")
    except Exception as e:
        print(f"⚠️  WebSocket Manager Redis 初始化失败: {e}")
        print("⚠️  WebSocket 将在单机模式下运行")
    
    yield
    
    # 关闭时：关闭 WebSocket Manager
    await wbs.close()
    
    # 关闭时：关闭数据库连接
    await Tortoise.close_connections()
    print("👋 数据库连接已关闭")


# 创建FastAPI应用
app = FastAPI(
    title="运动健身管理系统 - 后台管理端",
    description="基于RBAC权限模型的后台管理系统",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 导入并注册所有路由
from views.auth import auth_router
from views.admin_users import admin_user_router
from views.roles import role_router
from views.resources import resource_router
from views.business import business_router
from views.logs import log_router
from views.custser import custser_router

# 注册路由
app.include_router(auth_router)
app.include_router(admin_user_router)
app.include_router(role_router)
app.include_router(resource_router)
app.include_router(business_router)
app.include_router(log_router)
app.include_router(custser_router)

# CORS跨域配置
origins = [
    "http://localhost",
    "http://localhost:5173",  # 用户端前端
    "http://localhost:5174",  # 管理端前端
    "http://localhost:8001",  # 本地测试
    "http://127.0.0.1:5173",
    "http://127.0.0.1:5174",
    "http://127.0.0.1:8001",
    "*",  # 临时允许所有来源用于调试
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 临时允许所有来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"],
)


@app.get("/")
def read_root():
    """根路径：API信息"""
    return {
        "app": "运动健身管理系统 - 后台管理端",
        "version": "1.0.0",
        "port": 8001,
        "docs": "/docs"
    }


@app.middleware("http")
async def log_requests(request: Request, call_next):
    """记录请求日志和响应时间"""
    # 跳过 WebSocket 请求
    if request.url.path.startswith("/api/customer-service/ws/"):
        return await call_next(request)
    
    start_time = time.time()
    
    response = await call_next(request)
    
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    
    print(f"[{request.method}] {request.url.path} - {process_time:.3f}s")
    
    return response


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    print(f"❌ Global Exception: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": "Internal server error",
            "detail": str(exc)
        }
    )


if __name__ == '__main__':
    uvicorn.run("main:app", host="0.0.0.0", port=8001, reload=True)
